package cn.bone.springcloud.controller;

import cn.bone.springcloud.base.bean.CommonResult;
import cn.bone.springcloud.bean.Payment;
import cn.bone.springcloud.service.IPaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
@Slf4j
public class PaymentController {

    @Resource
    private IPaymentService paymentService;
    @Value("${server.port}")
    private String serverPort;

    @Resource
    private DiscoveryClient discoveryClient;

    @RequestMapping("/add")
    public CommonResult add(String serial){

        log.info("add with port:{}", serverPort);
        return paymentService.add(serial);
    }

    @RequestMapping("/get")
    public CommonResult get(Integer id){

        log.info("get with port:{}", serverPort);
        return paymentService.get(id);
    }


    @RequestMapping("/create")
    public CommonResult create(@RequestBody Payment payment){

        log.info("create with port:{}", serverPort);
        return paymentService.create(payment);
    }

    @RequestMapping("/payment/discovery")
    public Object discovery(){
        List<String> services = discoveryClient.getServices();
        services.forEach(s -> {
            log.info("服务列表清单: {}",s);
        });

        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        instances.forEach(i->{
            log.info("服务名称:{},\t实例名称:{},\t实例地址:{},\t端口号:{},\turl地址:{}",
                    i.getServiceId(),
                    i.getInstanceId(),
                    i.getHost(),
                    i.getPort(),
                    i.getUri());
        });

        return this.discoveryClient;
    }
}
